package com.FQJ.stock.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.FQJ.stock.constant.StockConstant;
import com.FQJ.stock.mapper.SysUserMapper;
import com.FQJ.stock.pojo.entity.SysUser;
import com.FQJ.stock.service.UserService;
import com.FQJ.stock.utils.IdWorker;
import com.FQJ.stock.vo.req.LoginReqVo;
import com.FQJ.stock.vo.resp.LoginRespVo;
import com.FQJ.stock.vo.resp.R;
import com.FQJ.stock.vo.resp.ResponseCode;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;



import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("userService")
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private IdWorker idWorker;


	@Override
	public SysUser getUserByUserName(String userName) {
		SysUser sysUser = sysUserMapper.getUserByUserName(userName);
		return sysUser;
	}

	@Override
	//javaWeb基础太差了，需要补一补
	public R<LoginRespVo> login(LoginReqVo vo) {
		//1.参数校验
		if (vo == null || StringUtils.isBlank(vo.getUsername()) || StringUtils.isBlank(vo.getPassword())) {
			return R.error(ResponseCode.DATA_ERROR.getMessage());
		}
		//2.校验验证码和sessionId是否有效
		if(StringUtils.isBlank(vo.getCode())|| StringUtils.isBlank(vo.getSessionId())){
			return R.error(ResponseCode.DATA_ERROR);
		}
		//3.根据Rkey从redis中缓存的校验证
		String rCode=(String)redisTemplate.opsForValue().get(StockConstant.CHECK_PREFIX+vo.getSessionId());
		//判断获取的验证码是否存在，以及是否与输入的验证码相同
		if (StringUtils.isBlank(rCode) || ! rCode.equalsIgnoreCase(vo.getCode())) {
			//验证码输入有误
			return R.error(ResponseCode.CHECK_CODE_ERROR);
		}
		//4.根据用户名查询用户信息
		SysUser user = sysUserMapper.getUserByUserName(vo.getUsername());
		//判断用户是否存在，存在密码校验比对
		if(user==null||!passwordEncoder.matches(vo.getPassword(),user.getPassword())){
			return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR.getMessage());
		}

		//4.响应
		LoginRespVo loginRespVo = new LoginRespVo();
		// loginRespVo.setUsername(vo.getUsername());
		// loginRespVo.setNickName(userByUserName.getNickName());
		// loginRespVo.setPhone(userByUserName.getPhone());
		// loginRespVo.setId(userByUserName.getId());
		//一个一个写太麻烦了，用Spring提供的工具类
		//必须保证属性名称和类型一致
		BeanUtils.copyProperties(user,loginRespVo);
		return R.ok(loginRespVo);
	}

	@Override
	public R<Map> getCaptchaCode() {//使用huTool,图片huTool来做的
		//参数分别是宽、高、验证码长度、干扰线数量
		LineCaptcha captcha = CaptchaUtil.createLineCaptcha(250, 40, 4, 5);
		//设置背景颜色清灰
		captcha.setBackground(Color.lightGray);
		String checkCode = captcha.getCode();//获取校验码
		log.info("生成校验码:{}",checkCode);
		//生成sessionId
		String sessionId = String.valueOf(idWorker.nextId());
		//将sessionId和校验码保存在redis下，并设置缓存中数据存活时间一分钟
		redisTemplate.opsForValue().set(StockConstant.CHECK_PREFIX +sessionId,checkCode,1, TimeUnit.MINUTES);
		//组装响应数据
		HashMap<String, String> info = new HashMap<>();
		info.put("sessionId",sessionId);
		info.put("imageData",captcha.getImageBase64());//获取base64格式的图片数据
		//设置响应数据格式
		return R.ok(info);
	}

}
